using Unity.Burst;
using Unity.Entities;
using Unity.Mathematics;
using Unity.Transforms;

namespace Kickball.Step1
{
    /// <summary>
    /// TransformSystemGroup 中会计算渲染矩阵，在该 system 之前执行可使得障碍物在当前帧显示，否则障碍物会在下一帧显示
    /// </summary>
    [UpdateBefore(typeof(TransformSystemGroup))]
    public partial struct ObstacleSpawnerSystem : ISystem
    {
        [BurstCompile]
        public void OnCreate(ref SystemState state)
        {
            state.RequireForUpdate<Execute.ObstacleSpawner>();
            state.RequireForUpdate<Config>();
        }

        [BurstCompile]
        public void OnUpdate(ref SystemState state)
        {
            state.Enabled = false; //只执行一次

            var config = SystemAPI.GetSingleton<Config>();

            var rand = new Unity.Mathematics.Random(123);
            var scale = config.ObstacleRadius * 2;

            for (int c = 0; c < config.ObstaclesNumColumns; c++)
            {
                for (int r = 0; r < config.ObstaclesNumRows; r++)
                {
                    //实例化
                    var obstacle = state.EntityManager.Instantiate(config.ObstaclePrefab);

                    state.EntityManager.SetComponentData(obstacle, new LocalTransform()
                    {
                        Position = new float3
                        {
                            x = (c * config.ObstacleGridCellSize) + rand.NextFloat(config.ObstacleOffset),
                            y = 0,
                            z = (r * config.ObstacleGridCellSize) + rand.NextFloat(config.ObstacleOffset),
                        },
                        Scale = scale,
                        Rotation = quaternion.identity,
                    });
                }
            }
        }
    }
}